/* 图片处理
 * ImageHandleAction.js
 */

import {uploadImgs,imglist} from '../api/ImageApi';

export function clearlist(){
	return {type:'LIST_IMAGE',datalist:[]};
}

/* 图片列表查询
 * 参数id 查询小于该id的数据
 * category_id 分类id
 * limit 表示查询多少条
 */
export function listImage(category_id=null,id=null,limit=null,callback=null){
	return (dispatch)=>{
		imglist({id:id,category_id:category_id,limit:limit})
		.then(result=>{
			if(result.code==200){
				dispatch({type:'LIST_IMAGE',datalist:result.data});
				if(callback) callback(result.data);
			}else{
				if(callback) callback(null);
			}

		})
		.catch(e=>{
			console.log('ImageHandleAction listImage error');
			console.log(e);
		});
	}
}

//分页点击下一页
export function nextPage(maxId,category_id=null,id=null,limit=null){
	//return {type:'IMAGE_LIST_NEXT_PAGE',maxId:maxId};
	return (dispatch)=>{
		imglist({id:id,category_id:category_id,limit:limit})
		.then(result=>{
			if(result.code==200){
				dispatch({type:'IMAGE_LIST_NEXT_PAGE',maxId:maxId,datalist:result.data});
			}
		})
		.catch(e=>{
			console.log('ImageHandleAction nextPage error');
			console.log(e);
		});
	}
}

//分页点击上一页
export function prePage(category_id=null,id=null,limit=null){
	//return {type:'IMAGE_LIST_PRE_PAGE'};
	return (dispatch)=>{
		imglist({id:id,category_id:category_id,limit:limit})
		.then(result=>{
			if(result.code==200){
				dispatch({type:'IMAGE_LIST_PRE_PAGE',datalist:result.data});
			}
		})
		.catch(e=>{
			console.log('ImageHandleAction prePage error');
			console.log(e);
		});
	}
}

export function uploadImage(files,category_id=0,callback=null){
	return (dispatch)=>{
		uploadImgs(files,category_id)
		.then(res=>{
			if(res.code==200){
				dispatch({type:'ADD_IMAGE',data:res.data});
				if(callback) callback(res.data.file);
			}else{
				if(callback) callback(null);
			}
		})
		.catch(e=>{
			console.log('ImageHandleAction upload image error');
			console.log(e);
			if(callback) callback(null);
		});
	}
}
